﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api.Domain;
using Top.Api.Util;

using System.Data;
using System.Data.SqlClient;

namespace TopApp.Library
{
    public class Database
    {
        private String server;
        private String name;
        private String user;
        private String pswd;

        private SqlConnection conn;
        public SqlCommand comm;

        private SqlConnection tConn;
        private SqlTransaction trans;
        public SqlCommand tComm;

        public Database( DBConfig config )
        {
            this.server = config.server;
            this.name = config.name;
            this.user = config.user;
            this.pswd = config.pswd;

            string connStr = "Data Source=" + this.server +
                ";UID=" + this.user +
                ";PWD=" + this.pswd;

            if (this.name !=null && this.name !="") connStr += ";Initial Catalog=" + this.name;

            this.conn = new SqlConnection(connStr);

            this.conn.Open();

            this.resetComm();
            this.resetTComm();
        }

        public void resetComm(){

            if (this.comm != null) this.comm.Dispose();
            this.comm = new SqlCommand("", this.conn);

        }

        public void resetTComm()
        {
            if (this.trans != null) this.trans.Dispose();
            if (this.tComm != null) this.tComm.Dispose();
            if (this.tConn != null)
            {
                this.tConn.Close();
                this.tConn.Dispose();
            }
            
            // 重新初始化
            this.tConn = new SqlConnection(
                "Data Source=" + this.server +
                ";UID=" + this.user +
                ";PWD=" + this.pswd +
                ";Initial Catalog=" + this.name);

            this.tConn.Open();
            this.beginTrans();
        }

        private void beginTrans()
        {
            this.trans = this.tConn.BeginTransaction();
            this.tComm = this.tConn.CreateCommand();
            this.tComm.Connection = this.tConn;
            this.tComm.Transaction = this.trans;
        }

        public void commit()
        {
            this.trans.Commit();
            this.beginTrans();
        }

        public void rollBack()
        {
            this.trans.Rollback();
            this.beginTrans();
        }
    }
}
